/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react';
import PropTypes from 'prop-types';
import {
  DeviceEventEmitter,
  InteractionManager,
  ListView,
  StyleSheet,
  ScrollView,
  View,
  Dimensions,
  Platform,
  Text
} from 'react-native';
import ScrollableTabView, {
  ScrollableTabBar
} from 'react-native-scrollable-tab-view';
import store from 'react-native-simple-store';

import LoadingView from '../../components/LoadingView';
import ToastUtil from '../../utils/ToastUtil';
import { getDataList, getTypeName, modifyList, getTeamSections } from '../../utils/ItemsUtil';
import ItemCell from '../../components/team-item-cell/TeamItemCell';
import Footer from '../../components/list/Footer';
import EmptyView from './EmptyView';
import ItemListView from './ItemListView';
import { DataProvider, LayoutProvider } from "recyclerlistview";
import TeamCard from '../../components/team/TeamCard';
import EditTeam from '../../components/team/EditTeam';

import * as types from '../../constants/ActionTypes';
const loadingBgImage = require("../../img/loading_placeholder.png");

const propTypes = {
  teamActions: PropTypes.object,
  team: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired
};

const ViewTypes = {
  FULL: 0,
  HALF_LEFT: 1,
  HALF_RIGHT: 2
};

const pages = [];
let page = 0;
const popoverHeight = 250;
let loadMoreTime = 0;
let currentLoadMoreTypeId;

class TeamSetting extends React.Component {
  constructor(props) {
    super(props);
    this._layoutProvider = this.teamLayoutProvider();

    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2
      }),
      dataProvider: new DataProvider((r1, r2) => {
        return r1 !== r2;
      }),
      isVisible: false,
      popoverRect: null,
      teamManager: {},
      teamMember: {},
      editTeamVisible: false,
      showAddDialog: false
    };

    this.onNavButtonPress = this.onNavButtonPress.bind(this);
    this.onSaveTeamSave = this.onSaveTeamSave.bind(this)
    this.onSaveTeamCancel = this.onSaveTeamCancel.bind(this)
    this.onRefresh = this.onRefresh.bind(this)
  }

  componentDidMount() {
    const { teamActions, team } = this.props;
    
    InteractionManager.runAfterInteractions(() => {
      if (!team.teamList) {
        let token;
        store.get('token')
        .then(freshToken => {
          token = freshToken;
          return store.get('site_id')
        })
        .then(site_id => teamActions.requestTeamList(token, site_id, true, false));
        page++;
        this.setState({editTeamVisible: true})
      }
    });
  }

  componentWillMount() {
    this.props.navigation.setParams({ handleCheck: this.onNavButtonPress });
  }

  componentWillReceiveProps(nextProps) {
    const { team, teamActions } = this.props;
    if (
      team.isLoadMore &&
      !nextProps.team.isLoadMore &&
      !nextProps.team.isRefreshing
    ) {
      if (nextProps.team.noMore) {
        ToastUtil.showShort('没有更多数据了');
        if (page >= 0) {
          page -= 1;
        }
      }
    }

    if (nextProps.team.type === types.EMPTY_TEAM_LIST && 
      team.teamList !== nextProps.teamList
    ) {
      if (this._alreadyReinit !== true) { 
        this._alreadyReinit = true
        let token;
        store.get('token')
        .then(freshToken => {
          token = freshToken;
          return store.get('site_id')
        })
        .then(site_id => teamActions.requestTeamList(token, site_id, true, false));
        page = 1;
      }
    }
  }

  onSaveTeamSave () {
    this.setState({showAddDialog: false})
    this.onRefresh()
  }

  onSaveTeamCancel() {
    this.setState({showAddDialog: false})
  }

  renderEditTeam = () => {
    if (this.state.showAddDialog) {
        return (<EditTeam {...this.props}
          visible={this.state.editTeamVisible} 
          user={this.props.user}
          onSave={this.onSaveTeamSave}
          teamActions={this.props.teamActions}
          onCancel={this.onSaveTeamCancel}
      />)
    }
  };

  componentWillUnmount() {
    const { teamActions } = this.props;
    this._alreadyReinit = false
    teamActions.resetTeamType()
  }

  closePopover = () => {
  }

  onRefresh = (typeId) => {
    const { teamActions } = this.props;
    let token;
    store.get('token')
    .then(freshToken => {
      token = freshToken;
      return store.get('site_id')
    })
    .then(site_id => teamActions.requestTeamList(token, site_id, true, false));
  };

  onPress = (team) => {
    this._alreadyReinit = false
    requestAnimationFrame(() => {
      const { navigate } = this.props.navigation;
      navigate('TeamProfile', { team });
    })
  };

  onIconClicked = () => {
    this.drawer.openDrawer();
  };

  onNavButtonPress () {
    this.setState({showAddDialog: true})
  };
  
  onEndReached = (typeId) => {
    const time = Date.parse(new Date()) / 1000;
    if (time - loadMoreTime > 1) {
      page += 1;
      const { teamActions } = this.props;
      let token;
      store.get('token')
        .then(freshToken => {
          token = freshToken;
          return store.get('site_id')
        })
        .then((site_id) => teamActions.requestTeamList(token, site_id, false, false, true, page));

      loadMoreTime = Date.parse(new Date()) / 1000;
    }
  };

  renderMembers = (memberList, isManager, title) => {
    return (
      memberList &&
      <TeamCard
        containerStyle={styles.memberItemStyle}
        sections={memberList}
      />
    )
  }

  renderFooter = () => {
    const { team } = this.props;
    return team.isLoadMore ? <Footer /> : <View />;
  };

  onPressItemHandler = (members, visible, type) => {
    visible = true
  }

  onManageExpand  = (expander, teamItem,  expanderVisible) => {
    const { team } = this.props;
    const mapping = {name: 'title', headimgurl: 'image', ding_user_id: 'key'}
    expander.measure((ox, oy, width, height, px, py) => {
      const rect = {x: px, y: py - popoverHeight + 50, width: width, height: height};
      team.teamList = modifyList(getDataList(team.teamList), teamItem.id, 'expanderVisible', true, (teamItem) => {
        return Object.assign({}, teamItem, {expanderVisible: true, managerRect: rect})
      })
      const managerSections = getTeamSections(teamItem.team_managers, mapping)
      const memberSections = getTeamSections(teamItem.team_members, mapping)
      this.setState({
        isVisible: true,
        popoverRect: rect,
        teamManager: {
          sections:[
            {data: managerSections, key: 'manager', title: '主管'},
            {data: memberSections, key: 'member', title: '成员'}
          ]
        }
      })
    });
  }


  renderItem = (type, team) => (
    <ItemCell team={team} onManageExpand={this.onManageExpand} onPressHandler={this.onPress} onPressItemHandler={this.onPressItemHandler} />
  );

  renderContent = () => {
    const { team } = this.props;
    if (team.loading) {
      return <LoadingView />;
    }
    const teamList =  getDataList(team.teamList)

    const isEmpty = teamList.length === 0;
    if (isEmpty) {
      return (
        <EmptyView team={team} onRefresh={this.onRefresh} />
      );
    }
    if (!this.teamList || this.teamList !== teamList) {
      this.teamList = teamList;
      this._dataSource = this.state.dataProvider.cloneWithRows(teamList);
    }
  
    const renderItem = this.renderItem;
    renderItem.bind(this);

    return (
      <ItemListView
        rowRenderer={renderItem}
        layoutProvider={this._layoutProvider}
        dataProvider={this._dataSource}
        data={teamList}
        isRefreshing={team.isRefreshing}
        onEndReached={this.onEndReached}
        onRefresh={this.onRefresh}
        renderFooter={this.renderFooter}
        renderItem={this.renderItem}
      />
    );
  };

  teamLayoutProvider () {
    let { width } = Dimensions.get("window");
    return new LayoutProvider(
      index => {return ViewTypes.FULL},
      (type, dim) => {
        dim.width = width;
        dim.height = 91;
      }
    )
  }

  render() {
    const { team } = this.props;
    const content = this.renderContent()
    const { height: SCREEN_HEIGHT, width: SCREEN_WIDTH } = Dimensions.get('window');
    const displayArea = {x: 10, y: 10, width: SCREEN_WIDTH - 20, height: SCREEN_HEIGHT}

    return (
      <View style={styles.container}>
        <View style={styles.base}>
        {content}
        </View>
        {this.renderEditTeam()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  base: {
    flex: 1,
  },
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff'
  },
  drawerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#ddd'
  },
  drawerTitleContent: {
    height: 120,
    justifyContent: 'flex-end',
    padding: 20,
    backgroundColor: '#3e9ce9'
  },
  drawerIcon: {
    width: 30,
    height: 30,
    marginLeft: 5
  },
  drawerTitle: {
    fontSize: 20,
    textAlign: 'left',
    color: '#fcfcfc'
  },
  drawerText: {
    fontSize: 18,
    marginLeft: 15,
    textAlign: 'center',
    color: 'black'
  },
  timeAgo: {
    fontSize: 14,
    color: '#aaaaaa',
    marginTop: 5
  },
  refreshControlBase: {
    backgroundColor: 'transparent'
  },
  tab: {
    paddingBottom: 0
  },
  tabText: {
    fontSize: 16
  },
  tabBarUnderline: {
    backgroundColor: '#3e9ce9',
    height: 2
  },
  content: {
    backgroundColor: 'white',
    borderRadius: 6,
  },
  memberItemStyle: {
    height: popoverHeight,
    width: 260
  }
});

TeamSetting.propTypes = propTypes;

export default TeamSetting;
